var HtmlParser = require('htmlParseUtil.js');
var md5 = require('md5.js');
var requests = require('request.js');

/*String.prototype.trim = function() {
  return this.replace( /(^\s*)|(\s*$)/g, '' );
}*/

String.prototype.isEmpty = function () {
  return this.trim() == '';
}

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 获取当前日期对象
 * @ returns {object}
 */
function getCurrentData() {
  var date = new Date();
  return {
    date: new Date(),
    year: date.getFullYear(),
    month: date.getMonth() + 1,
    day: date.getDate(),
    weekday: date.getDay()
  };
}

/**
 * 快捷方法 获取HtmlParser对象
 * @param {string} html html文本
 * @return {object} HtmlParser
 */
function $(html) {
  return new HtmlParser(html);
}

/**
 * 解析story对象的body部分
 * @param {string} html body的html文本
 * @param {boolean} isDecode 是否需要unicode解析
 * @return {object} 解析后的对象
 */
function parseStory(html, isDecode) {
  var questionArr = $(html).tag('div').attr('class', 'question').match();
  var stories = [];
  var $story;
  if (questionArr) {
    for (var i = 0, len = questionArr.length; i < len; i++) {
      $story = $(questionArr[i]);
      var mavatar = getArrayContent(getArrayContent($story.tag('div').attr('class', 'meta').match()).jhe_ma('img', 'src'));
      mavatar = mavatar.replace("pic1", "pic3");
      mavatar = mavatar.replace("pic2", "pic3");
      stories.push({
        title: getArrayContent($story.tag('h2').attr('class', 'question-title').match()),
        avatar: mavatar,
        author: getArrayContent($story.tag('span').attr('class', 'author').match()),
        bio: getArrayContent($story.tag('span').attr('class', 'bio').match()),
        content: parseStoryContent($story, isDecode),
        more: getArrayContent(getArrayContent($(html).tag('div').attr('class', 'view-more').match()).jhe_ma('a', 'href'))
      });
    }
  }
  return stories;
}

/**
 * 解析文章内容
 * @param {string} $story htmlparser对象
 * @param {boolean} isDecode 是否需要unicode解析
 * @returb {object} 文章内容对象
 */
function parseStoryContent($story, isDecode) {
  var content = [];
  var ps = $story.tag('p').match();
  var p, strong, img, blockquote, em;
  if (ps) {
    for (var i = 0, len = ps.length; i < len; i++) {
      p = transferSign(ps[i]); //获取<p>的内容 ,并将特殊符号转义
      if (!p || p.isEmpty())
        continue;

      img = getArrayContent((p.jhe_ma('img', 'src')));
      strong = getArrayContent(p.jhe_om('strong'));
      em = getArrayContent(p.jhe_om('em'));
      blockquote = getArrayContent(p.jhe_om('blockquote'));

      if (!img.isEmpty()) { //获取图片
        img = img.replace("pic1", "pic3");
        img = img.replace("pic2", "pic3");
        content.push({
          type: 'img',
          value: img
        });
      } else if (isOnly(p, strong)) { //获取加粗段落<p><strong>...</strong></p>
        strong = decodeHtml(strong, isDecode);
        if (!strong.isEmpty())
          content.push({
            type: 'pstrong',
            value: strong
          });
      } else if (isOnly(p, em)) { //获取强调段落 <p><em>...</em></p>
        em = decodeHtml(em, isDecode);
        if (!em.isEmpty())
          content.push({
            type: 'pem',
            value: em
          });
      } else if (isOnly(p, blockquote)) { //获取引用块 <p><blockquote>...</blockquote></p>
        blockquote = decodeHtml(blockquote, isDecode);
        if (!blockquote.isEmpty())
          content.push({
            type: 'blockquote',
            value: blockquote
          });
      } else { //其他类型 归类为普通段落 ....太累了 不想解析了T_T
        p = decodeHtml(p, isDecode);
        if (!p.isEmpty())
          content.push({
            type: 'p',
            value: p
          });
      }
    }
  }
  return content;
}

/**
 * 取出多余或者难以解析的html并且替换转义符号
 */
function decodeHtml(value, isDecode) {
  if (!value) return '';
  value = value.replace(/<[^>]+>/g, '')
    .replace(/&nbsp;/g, ' ')
    .replace(/&ldquo;/g, '"')
    .replace(/&rdquo;/g, '"').replace(/&middot;/g, '·');
  if (isDecode)
    return decodeUnicode(value.replace(/&#/g, '\\u'));
  return value;

}

/**
 * 解析段落的unicode字符，主题日报中的内容又很多是编码过的
 */
function decodeUnicode(str) {
  var ret = '';
  var splits = str.split(';');
  for (let i = 0; i < splits.length; i++) {
    ret += spliteDecode(splits[i]);
  }
  return ret;
};

/**
 * 解析单个unidecode字符
 */
function spliteDecode(value) {
  var target = value.match(/\\u\d+/g);
  if (target && target.length > 0) { //解析类似  "7.1 \u20998" 参杂其他字符
    target = target[0];
    var temp = value.replace(target, '{{@}}');
    target = target.replace('\\u', '');
    target = String.fromCharCode(parseInt(target));
    return temp.replace("{{@}}", target);
  } else {
    // value = value.replace( '\\u', '' );
    // return String.fromCharCode( parseInt( value, '10' ) )
    return value;
  }
}

/**
 * 获取数组中的内容（一般为第一个元素）
 * @param {array} arr 内容数组
 * @return {string} 内容
 */
function getArrayContent(arr) {
  if (!arr || arr.length == 0) return '';
  return arr[0];
}

function isOnly(src, target) {
  return src.trim() == target;
}

/**
 * 判断目标是否是函数
 * @param {mixed} val
 * @returns {boolean}
 */
function isFunction(val) {
  return typeof val === 'function';
}


/**
 * 修正图片url，将pic1和pic2改为pic4
 * @param data
 * @returns {*}
 */
function correctData(data) {
  if (("top_stories" in data)) {
    var top_stories = data.top_stories;
    for (var i = 0; i < top_stories.length; i++) {
      top_stories[i].image = top_stories[i].image.replace("pic1", "pic4");
      top_stories[i].image = top_stories[i].image.replace("pic2", "pic4");
    }
    data.top_stories = top_stories;
  }

  var stories = data.stories;
  for (var i = 0; i < stories.length; i++) {
    if (("images" in stories[i])) {
      var s = stories[i].images[0];
      s = s.replace("pic1", "pic4");
      s = s.replace("pic2", "pic4");
      stories[i].images[0] = s;
    }
  }

  data.stories = stories;
  return data;
}
const getYear = time => {
  var date = new Date(time);
  var year = date.getFullYear()
  return year
}

// 对月份进行处理，1-9月在前面添加一个“0”
// if (nowMonth >= 1 && nowMonth <= 9) {
//   nowMonth = "0" + nowMonth;
// }




const getMonth = time => {
  var date = new Date(time);
  var month = date.getMonth() + 1
  return month
}
/**
 * 将转义字符转为实体
 * @param data
 * @returns {*}
 */
function transferSign(data) {
  data = data.replace(/&ndash;/g, "–");
  data = data.replace(/&mdash;/g, "—");
  data = data.replace(/&hellip;/g, "…");
  data = data.replace(/&bull;/g, "•");
  data = data.replace(/&rsquo;/g, "’");
  data = data.replace(/&ndash;/g, "–");
  return data;
}

/**
 * 请求接口签名 2021.10.28
 * @param data
 * @returns encrypt
 */
// 数据加密
function sort(data) {
  var keys = Object.keys(data).sort();
  var result = {};
  for (var i = 0; i < keys.length; i++) {
    var key = keys[i];
    result[key] = data[key];
  }
  return result;
}

function mtRand(min, max) {
  var result = Math.random() * (max - min + 1) + min;
  return parseInt(result);
}

function getSignature(appkey, json) {
  json.timestamp = Date.parse(new Date()) / 1000;
  json.nonce_str = mtRand(100000, 999999);
  json = sort(json);
  var str = '';
  for (var k in json) {
    if (str != '')
      str += '&'
    str += k + '=' + json[k]
  }
  str += '&key=' + appkey;
  json.key = appkey;
  json.sign = md5.md5(str);
  //sconsole.log(str);
  //console.log(json.sign);
  delete json.key;
  return json;
}

// 请求接口签名 2021.10.28 结束


// 判断日期是不是今天、昨天、明天
export const isToday = (str) => {
  let d = new Date(str).setHours(0, 0, 0, 0);
  let today = new Date().setHours(0, 0, 0, 0);

  let obj = {
    '-86400000': '0',
    0: '1', //今天
    86400000: '2',
  };

  return obj[d - today] || '3';
};

//验证码倒计时 2022.4.3
function countdown(that, length) {
  console.log('count down');
  var seconds = that.data.seconds;
  console.log(seconds);
  var captchaLabel = that.data.captchaLabel;
  if (seconds <= 1) {
    captchaLabel = '获取验证码';
    seconds = length;
    that.setData({
      captchaDisabled: false
    });
  } else {
    captchaLabel = --seconds + '秒后重新发送'
  }
  that.setData({
    seconds: seconds,
    captchaLabel: captchaLabel
  });
};

// Canvas绘制海报 2022.4.5
const promisify = (api) => {
  return (options, ...params) => {
    return new Promise((resolve, reject) => {
      const extras = {
        success: resolve,
        fail: reject
      }
      api({
        ...options,
        ...extras
      }, ...params)
    })
  }
}


//用户的确认弹窗封装成同步状态确认 2022.4.14
const linYuFanShowModal = (title, content) => {
  return new Promise((reslove, reject) => {
    wx.showModal({
      title,
      content,
      success(res) {
        if (res.confirm) {
          var confirmStatus = true
          reslove(confirmStatus);
        } else if (res.cancel) {
          var confirmStatus = false
          reslove(confirmStatus);
        }
      }
    })
  })
}
//用户的确认弹窗封装成同步状态确认 2022.4.14


//封装成同步wx.login 2022.4.14
const linYuFanWxLogin = () => {
  return new Promise((reslove) => {
    wx.login({
      success(login_res) {
        reslove(login_res.code);
      }
    })
  })
}
//封装成同步wx.login 2022.4.14


/**
 * 替换时间字符串，把时间替换成上午，下午的形式 2022.4.26
 * @param {*} timeStr 
 */
function replaceTimeStr(timeStr) {
  if (timeStr.indexOf('00:00:00') >= 1) {
    if (timeStr != null) {
      timeStr = timeStr.replace("00:00:00", "上午")
      return timeStr
    }

  } else if (timeStr.indexOf("12:00:00") >= 1) {
    if (timeStr != null) {
      timeStr = timeStr.replace("12:00:00", "下午")
      return timeStr
    }
  } else {
    return '时间不正确'
  }
  return timeStr
}
//替换时间字符串 2022.4.26


//节假日时间去重，以班主任自定时间优先计算 2022.4.30
function delRepeatDate(arr) {
  let newArr = Array.from(arr); // 复制一份数组
  for (var i = 0; i < newArr.length - 1; i++) {
    for (var j = i + 1; j < newArr.length; j++) {
      // console.log('newArr[i]', newArr[i])
      // console.log('newArr[j]', newArr[j])
      // console.log('\n')
      if (newArr[i].date_time == newArr[j].date_time) {
        if (newArr[j].is_system === 1) {
          // console.log('删除',newArr[j])
          newArr.splice(j, 1); // 将重复元素删掉
          j--; // 删掉重复元素后下一位元素向前移动一位所以j--
        } else {
          // console.log('删除',newArr[i])
          newArr.splice(i, 1); // 将重复元素删掉
          i--; // 删掉重复元素后下一位元素向前移动一位所以i--
        }
      }
    }
  }
  return newArr;
}
//节假日时间去重，以班主任自定时间优先计算 2022.4.30



/**
 * 标准日期格式化
 * **/
function dateFormat(fmt, date) {
  let ret;
  const opt = {
    'Y+': date.getFullYear().toString(), // 年
    'm+': (date.getMonth() + 1).toString(), // 月
    'd+': date.getDate().toString(), // 日
    'H+': date.getHours().toString(), // 时
    'M+': date.getMinutes().toString(), // 分
    'S+': date.getSeconds().toString() // 秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };
  for (let k in opt) {
    ret = new RegExp('(' + k + ')').exec(fmt);
    if (ret) {
      fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, '0')))
    };
  };
  return fmt;
}
// 用法
// let curDate;
// curDate = new Date();
// curDate = dateFormat('YYYY-mm-dd HH:MM:SS', curDate)

//只从标准时间里获取时、分、秒
// curDate = dateFormat('HH:MM:SS', curDate)



/*
 *@ClassAuthor: 林羽凡 Linyufan.com
 *@Date: 2022-06-07 10:40:04
 *@Description: 通过某一天，获取这个月所有的日期
 */
function allMontDays(res = new Date()) {
  /**
   * 获取一个月多少天，并获取月初星期几
   */
  const daxier = ['一', '二', '三', '四', '五', '六', '日'];
  const date = new Date(res)
  const y = date.getFullYear()
  const m = date.getMonth() + 1
  var date2 = new Date(y, m, 0)
  var rq = date2.getDate() // 日 本月最后一天

  var xq = date2.getDay(); // 星期 本月第一天星期几  new Date(0).getDay()
  var rq2 = rq % 7
  if (rq2 === 0) {
    xq = rq2 + 1
  } else {
    if (rq2 > xq) xq += 7
    xq = xq - rq2
  }

  var data = [];
  for (var i = 1; i <= rq; i++) {
    var ms = m + 1 < 10 ? "0" + m : m; // 月份小于10拼接0
    var is = i < 10 ? "0" + i : i; // 日小于10拼接0
    data.push(
      y + '-' + ms + '-' + is,
      // 'xq': daxier[xq], //显示星期的，暂时不要了
    )

    xq = (++xq == 7) ? 0 : xq
  }
  return data;
}



function computedTimes(n1, n2, n3 = 0) {
  if (n1) var date = new Date(n1, n2, n3);
  else var date = new Date();

  let y = date.getFullYear();
  let m = date.getMonth();
  let d = date.getDate();
  return {
    y,
    m,
    d
  };
}

/*
 *@ClassAuthor: 林羽凡 Linyufan.com
 *@Date: 2022-06-06 14:52:21
 *@Description: 获取当前日期 N 天之前的所有日期
 */
function getBeforeDate(dateDate = 30) {
  let times = computedTimes();
  var y = times.y;
  var m = times.m;
  var d = times.d;
  var dateNum = dateDate; // 双向绑定 - 展示天数
  var dataKey = []; // 下标 存日期
  while (true) {
    for (var i = d; i > d - dateNum; i--) {
      if (i == 0) break;
      var ms = m + 1 < 10 ? "0" + (m + 1) : m + 1; // 月份小于10拼接0
      var is = i < 10 ? "0" + i : i; // 日小于10拼接0
      // dataKey[ms + "" + is] = m + 1 + "月" + i + "日";
      dataKey = dataKey.concat(y + '-' + ms + "-" + is);
    }

    if (dateNum - d >= 0) {
      // 判断减去当月天数是否还不满足展示天数
      dateNum = dateNum - d;
      let datas = computedTimes(y, m);
      y = datas.y;
      m = datas.m;
      d = datas.d;
    } else break;
  }
  return dataKey;
}

/*
 *@ClassAuthor: 林羽凡 Linyufan.com
 *@Date: 2022-06-06 14:55:11
 *@Description: 获取当前日期后 N 天
 */
export function getAfterDate(dateDate = 30) {
  //当前日期的前七天
  var myDate = new Date();
  // myDate.setDate(myDate.getDate() - dateDate);  //后7天就把该行代码注释
  var dateArray = [];
  var dateTemp;
  var flag = 1;
  for (var i = 0; i < dateDate; i++) {
    var year = myDate.getFullYear();
    var month = myDate.getMonth() + 1;
    var date = myDate.getDate();
    var date = myDate.getDate();
    month < 10 ? (month = "0" + month) : month;
    date < 10 ? (date = "0" + date) : date;
    dateTemp = year + '-' + month + "-" + date;
    dateArray.push(dateTemp);
    myDate.setDate(myDate.getDate() + flag);
  }
  return dateArray;
}


module.exports = {
  getBeforeDate, //获取当前日期 N 天之前的所有日期 2022.7.11
  getAfterDate, //获取当前日期后 N 天 2022.7.11
  allMontDays, //通过某一天，获取这个月所有的日期2022.6.27
  dateFormat, //将标准时间格式化为指定日期时间格式 2022.6.19
  delRepeatDate, //节假日时间去重，以班主任自定时间优先计算 2022.4.30
  replaceTimeStr, //替换时间字符串 2022.4.26
  linYuFanWxLogin, //封装成同步wx.login 2022.4.14
  linYuFanShowModal, //封闭成同步状态确认 2022.4.14
  promisify, //Canvas绘制海报 2022.4.5
  countdown, //验证码倒计时 2022.4.3
  formatTime,
  getCurrentData,
  isFunction,
  parseStory,
  correctData,
  transferSign,

  getYear,
  getMonth,

  getSignature, //加密签名 2021.10.28
  isToday,

}